﻿using Abp.Extensions;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Mt.Site.Core.BadWordsFilters
{
    /// <summary>
    /// 针对内容dictonary类型,敏感词过滤
    /// </summary>
    [AttributeUsage(AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.Property)]
    public class ContentBadWordValiateAttribute: ValidationAttribute
    {
        private string[] Fileds { get; set; }

        public ContentBadWordValiateAttribute(params string[] fileds)
        {
            this.Fileds = fileds;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (!(value is Dictionary<string,string>) || Fileds.Length == 0)
            {
                return ValidationResult.Success;
            }

            var _badWordFilterManager = validationContext.GetRequiredService<IBadWordFilterManager>();

            var dic = value as Dictionary<string,string>;
            foreach (var item in Fileds)
            {
                if (dic.ContainsKey(item.ToCamelCase()))
                {
                    var txt = Convert.ToString(dic[item.ToCamelCase()]);
                    var str = _badWordFilterManager.CheckBadWords(txt);
                    if (!string.IsNullOrWhiteSpace(str))
                    {
                        return new ValidationResult(str);
                    }
                }
            }
            
            return ValidationResult.Success;
        }
    }
}
